package pers.xx.sbm.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;
import pers.xx.sbm.entity.User;

/**
 * @author ：xiexing
 * @description：获取当前用户
 * @date ：2020/10/12 10:20
 */
@Repository
public class UserUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private User user;//单例模式获取user


    /**
     * @description 获取当前用户
     * @author XieXing
     * @date 2020/10/12 11:26
     */
    public User getCurrentUser() {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        JSONObject user = JSONObject.parseObject(opsForValue.get("user:" + TokenUtils.getToken()));  // 转换为json
        if (user == null) {
            return null;
        }
        User currentUser = getUser();
        currentUser.setUserName(user.getString("userName"));//设置用户名
        currentUser.setId(user.getInteger("id"));//设置用户id
        currentUser.setUserSysName(user.getString("userSysName"));//设置所属系统名称
        return currentUser;
    }

    /**
     * @description 获取当前user
     * @author XieXing
     * @date 2020/10/12 10:24
     */
    private User getUser() {
        if (user == null) {
            user = new User();
        }
        return user;
    }
}
